package com.sunyard.pcc.common.validator;

import com.sunyard.pcc.common.constant.ErrorCodeEnum;
import com.sunyard.pcc.common.exception.PccCommonException;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;

/**
 * @Author: Hewei
 * @Description:
 * @Date: Created in 11:18 2018/2/27
 */
public class ValidationUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }


    /**
     * 对象校验
     * @param obj 待校验对象
     * @param <T>
     * @throws PccCommonException
     */
    public static <T> void validateEntity(T obj) throws PccCommonException {
        Optional.ofNullable(obj)
                .orElseThrow(() -> new PccCommonException(ErrorCodeEnum.PARAM_EMPTY));

        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, Default.class);
        if (!constraintViolations.isEmpty()){
            ConstraintViolation<T> constraintViolation = constraintViolations.iterator().next();
            throw new PccCommonException(ErrorCodeEnum.PARAM_ERROR.getErrorCode(), constraintViolation.getMessage());
        }
    }

    /**
     * 参数为空判断
     * @param objs
     * @throws PccCommonException
     */
    public static void isBlank(Object... objs) throws PccCommonException {
        for (Object obj : objs){
            Optional.ofNullable(obj)
                    .orElseThrow(() -> new PccCommonException(ErrorCodeEnum.PARAM_EMPTY));
        }
    }


    public static <T> void isBlank(Collection<T>... collections) throws PccCommonException {
        for (Collection<T> collection : collections){
            if (CollectionUtils.isEmpty(collection)){
                throw new PccCommonException(ErrorCodeEnum.PARAM_EMPTY);
            }
        }
    }




}
